package com.xzbd.gef.view;


import org.eclipse.draw2d.AbstractBorder;
import org.eclipse.draw2d.ColorConstants;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.Graphics;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.ToolbarLayout;
import org.eclipse.draw2d.geometry.Insets;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.draw2d.text.BlockFlow;
import org.eclipse.draw2d.text.FlowPage;
import org.eclipse.draw2d.text.ParagraphTextLayout;
import org.eclipse.draw2d.text.TextFlow;
import org.eclipse.swt.SWT;

import com.xzbd.core.SerializableColor;

public class NotesNodeFigure extends Figure {
	TextFlow labelNotes;

	public NotesNodeFigure() {
		ToolbarLayout layout = new ToolbarLayout();
		setLayoutManager(layout);

		FlowPage page = new FlowPage();
		page.setForegroundColor(ColorConstants.black);
		setBackgroundColor(ColorConstants.white);
		BlockFlow block = new BlockFlow();
		labelNotes = new TextFlow();
		labelNotes.setLayoutManager(new ParagraphTextLayout(labelNotes, ParagraphTextLayout.WORD_WRAP_SOFT));
		block.add(labelNotes);
		page.add(block);
		setOpaque(true);
		add(page);

		setBorder(new NoteBorder());
	}

	protected void paintFigure(Graphics graphics) {
		Rectangle b = getBounds();
		final int fold = NoteBorder.FOLD;
		graphics.fillRectangle(b.x + fold, b.y, b.width - fold, fold);
		graphics.fillRectangle(b.x, b.y + fold, b.width, b.height - fold);
		super.paintFigure(graphics);
	}

	public void setColor(SerializableColor color) {
		setBackgroundColor(color.getColor());
	}

	public void setNotes(String text) {
		labelNotes.setText(text);
	}

	public void setLayout(Rectangle rect) {
		getParent().setConstraint(this, rect);
	}

	public class NoteBorder extends AbstractBorder {
		public static final int FOLD = 10;

		@Override
		public Insets getInsets(IFigure arg0) {
			return new Insets(1, 2 + FOLD, 2, 2);
		}

		@Override
		public void paint(IFigure figure, Graphics graphics, Insets insets) {
			Rectangle r = figure.getBounds().getCopy();
			r.crop(insets);
			graphics.setLineWidth(1);

			graphics.drawLine(r.x + FOLD, r.y, r.x + r.width - 1, r.y);
			graphics.drawLine(r.x, r.y + FOLD, r.x, r.y + r.height - 1);
			graphics.drawLine(r.x + r.width - 1, r.y, r.x + r.width - 1, r.y + r.height - 1);
			graphics.drawLine(r.x, r.y + r.height - 1, r.x + r.width - 1, r.y + r.height - 1);

			graphics.drawLine(r.x + FOLD, r.y, r.x + FOLD, r.y + FOLD);
			graphics.drawLine(r.x, r.y + FOLD, r.x + FOLD, r.y + FOLD);

			graphics.setBackgroundColor(ColorConstants.lightGray);
			graphics.fillPolygon(new int[] { r.x, r.y + FOLD, r.x + FOLD, r.y, r.x + FOLD, r.y + FOLD });

			graphics.setLineStyle(SWT.LINE_DOT);
			graphics.drawLine(r.x, r.y + FOLD, r.x + FOLD, r.y);
		}
	}

}
